<template>
  <div class="main-content">
    <div style="height: auto;">
      <OperationPanel
        @execute-click="executeSQL"
        :enableExecuteBtn="enableExecuteBtn"
      ></OperationPanel>
    </div>
    <div style="height: 100%;"><SplitContent ref="splitContent"></SplitContent></div>
  </div>
</template>

<script>
import SplitContent from '@/components/SplitContent.vue';
import OperationPanel from '@/components/OperationPanel.vue';
import httpRequest from '@/utils/httpRequest';
import errors from '@/utils/errors';
import errorHandler from '@/utils/errorHandler';
import { SQL_RESULT_TYPE } from '@/utils/constants';

export default {
  name: 'MainContent',
  components: {
    SplitContent,
    OperationPanel,
  },
  data() {
    return {
      contentOprator: null,
      enableExecuteBtn: true,
      readOnlyEditor: true,
    };
  },
  methods: {
    showDirectionT(direction) {
      // console.log(direction);
      this.contentOprator.showDirection(direction.markdown);
    },
    printFailedResult(cause) {
      this.contentOprator.setResult('代码执行失败...');
      this.contentOprator.closeTable();
      if (cause) {
        this.contentOprator.appendResult(cause);
      }
    },
    printSuccessedResult(result) {
      this.contentOprator.setResult('代码执行成功!');
      this.contentOprator.appendResult(`耗时: ${result.time_consuming / 1000}s`);
      this.contentOprator.closeTable();
      if (result.type === SQL_RESULT_TYPE.UNKNOWN) {
        this.contentOprator.appendResult('服务器未返回任何数据...');
        return;
      }
      if (result.type === SQL_RESULT_TYPE.UPDATE) {
        this.contentOprator.appendResult(`共${result.updateCount}条数据已被更新!`);
      } else if (result.type === SQL_RESULT_TYPE.QUERY) {
        this.contentOprator.showTable(result.table);
      }
    },
    SQLErrorHandler(resp) {
      this.printFailedResult(resp.data.msg);
    },
    validateSQL(sql) {
      if (sql === '') {
        throw errors.OperationError('你还未输入sql语句, 无法执行.');
      }
      return sql;
    },
    beforeExecuteSQL() {
      this.contentOprator.readOnlySQLEditor(true);
      this.enableExecuteBtn = false;
    },
    afterExecuteSQL() {
      this.contentOprator.readOnlySQLEditor(false);
      this.enableExecuteBtn = true;
    },
    handleData(resp) {
      const result = {};
      result.type = resp.data.type;
      if (result.type === SQL_RESULT_TYPE.QUERY) {
        result.table = {
          fields: resp.data.metaData.fields,
          data: resp.data.data,
        };
      }
      result.time_consuming = resp.data.time_consuming;
      result.updateCount = resp.data.updateCount;
      this.printSuccessedResult(result);
    },
    executeSQL() {
      // 获取sql并验证有效性
      const sql = this.validateSQL(this.contentOprator.getSQL());

      this.beforeExecuteSQL();
      this.contentOprator.setResult('正在执行sql语句...');

      // 发送sql到服务器
      httpRequest
        .post('sql/execute', {
          data: { sql },
        })
        .then((resp) => {
          const { codes } = httpRequest;
          switch (resp.data.code) {
            case codes.SUCCESS:
              this.handleData(resp);
              this.afterExecuteSQL();
              break;
            case codes.NOT_LOGIN:
              this.$store.dispatch('logout');
              throw errors.ApiError(resp.data.msg);
            case codes.FAILURE:
              throw errors.ApiError(resp.data.msg);
            default:
              throw errors.WarningError(resp.data.msg);
          }
        })
        .catch((err) => {
          this.printFailedResult(err.message);
          this.afterExecuteSQL();
          errorHandler(err);
        });
    },
    test() {
      this.contentOprator.readOnlySQLEditor(this.readOnlyEditor);
      this.readOnlyEditor = !this.readOnlyEditor;
    },
  },
  mounted() {
    this.contentOprator = this.$refs.splitContent;
  },
};
</script>

<style>
.main-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  border-left: solid 1px #e4e7ed;
}
</style>
